//
//  HMaskWIndowManager+Keyboard.swift
//  Drop
//
//  Created by hushaohua on 2017/12/17.
//  Copyright © 2017年 init. All rights reserved.
//

import Foundation
import UIKit

extension HMaskWindowManager{
    func addKeyboardObserver() -> Void {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChanged(_:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: Notification.Name.UIKeyboardDidShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: Notification.Name.UIKeyboardDidHide, object: nil);
    }
    
    func removeKeyboardObserver() -> Void {
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillChangeFrame, object: nil);
    }
    
    @objc func keyboardDidShow(_ notification:NSNotification){
        self.keyboardDidAppear = true;
    }
    @objc func keyboardDidHide(_ notification:NSNotification){
        self.keyboardDidAppear = false;
    }
    
    @objc func keyboardWillChanged(_ notification:NSNotification){
        //        var beginFrame = notification.userInfo![UIKeyboardFrameBeginUserInfoKey];
        var frame = self.backgroundView!.frame;
        let endFrame:CGRect = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect;
        var duration:TimeInterval = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval;
        var dismissAfterKeyboard = false;
        if (endFrame.origin.y < UIScreen.main.bounds.size.height){
            frame.origin.y = endFrame.minY - self.backgroundView!.bounds.size.height;
        }else{
            let vel:CGFloat = (endFrame.minY - frame.size.height) / CGFloat(duration);
            frame.origin.y = endFrame.minY;
            duration = duration + TimeInterval(frame.size.height / vel);
            dismissAfterKeyboard = true;
        }
        
        let curve:Int = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int;
        let option:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: UInt(curve));
        UIView.animate(withDuration: duration, delay: 0, options: option, animations: {
            if (dismissAfterKeyboard){
                self.window.alpha = 0;
            }
            self.backgroundView!.frame = frame;
        }) { (finished) in
            if (dismissAfterKeyboard){
                self.clearHolderViews();
            }
        }
    }
}
